package com.danjinwulian.web.controller.iot;

import com.alibaba.fastjson2.JSON;
import com.danjinwulian.iot.service.TencentIotService;
import com.danjinwulian.common.annotation.Log;
import com.danjinwulian.common.constant.IoTConstants;
import com.danjinwulian.common.core.controller.BaseController;
import com.danjinwulian.common.core.domain.AjaxResult;
import com.danjinwulian.common.core.domain.entity.IotProduct;
import com.danjinwulian.common.core.page.TableDataInfo;
import com.danjinwulian.common.enums.BusinessType;
import com.danjinwulian.common.utils.StringUtils;
import com.danjinwulian.device.service.IIotProductService;
import com.tencentcloudapi.iotexplorer.v20190423.models.*;
import jodd.typeconverter.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 产品信息
 *
 * @author ken.h
 */
@RestController
@RequestMapping("/device/product")
public class IotProductController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(IotProductController.class);

    @Autowired
    private IIotProductService productService;
    @Autowired
    private TencentIotService tencentIotService;

    /**
     * 获取产品列表
     */
    @PreAuthorize("@ss.hasPermi('device:product:import')")
    @GetMapping("/import")
    public AjaxResult importProduct()
    {
        AjaxResult ajax = AjaxResult.success();

        try {
            // 调用腾讯云物联网开发平台获取产品列表
            GetStudioProductListResponse response = tencentIotService.getProductList(0L, 10L);

            if (response != null && response.getProducts() != null) {
                // 将腾讯云产品数据转换为本地产品数据
                for (ProductEntry productEntry : response.getProducts()) {
                    IotProduct iotProduct = productService.selectProductById(productEntry.getProductId());
                    if (iotProduct != null) {
                        iotProduct = getIotProduct(productEntry);
                        iotProduct.setUpdateBy(getUsername());
                        productService.updateProduct(iotProduct);
                    } else {
                        iotProduct = getIotProduct(productEntry);
                        iotProduct.setCreateBy(getUsername());
                        productService.insertProduct(iotProduct);
                    }
                }
                ajax = AjaxResult.success();
            }
        } catch (Exception e) {
            logger.error("导入产品列表失败", e);
            ajax = AjaxResult.error("导入物联网平台产品失败，" + e.getMessage());
        }

        return ajax;
    }

    /**
     * 获取产品列表
     */
    @PreAuthorize("@ss.hasPermi('device:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(IotProduct product)
    {
        startPage();
        List<IotProduct> list = productService.selectProductList(product);
        return getDataTable(list);

//        try {
//            // 调用腾讯云物联网开发平台获取产品列表
//            GetStudioProductListResponse response = tencentIotService.getProductList(0L, 10L);
//
//            if (response != null && response.getProducts() != null) {
//                // 将腾讯云产品数据转换为本地产品数据
//                List<IotProduct> productList = new ArrayList<>();
//                for (ProductEntry productEntry : response.getProducts()) {
//                    IotProduct iotProduct = getIotProduct(productEntry);
//                    productList.add(iotProduct);
//                }
//                return getDataTable(productList);
//            } else {
//                return getDataTable(new ArrayList<>());
//            }
//        } catch (Exception e) {
//            logger.error("获取产品列表失败", e);
//            return getDataTable(new ArrayList<>());
//        }
    }

    private static IotProduct getIotProduct(ProductEntry productEntry) {
        IotProduct iotProduct = new IotProduct();
        iotProduct.setProductId(productEntry.getProductId());
        iotProduct.setProductName(productEntry.getProductName());
        iotProduct.setProductDesc(productEntry.getProductDesc());
        iotProduct.setProductKey("");
        iotProduct.setProductSecret(""); // 腾讯云不需要产品密钥
        iotProduct.setProductType(productEntry.getProductType());
        iotProduct.setCategoryId(productEntry.getCategoryId());
        iotProduct.setEncryptionType(productEntry.getEncryptionType());
        iotProduct.setNetType(productEntry.getNetType());
        iotProduct.setRegion(productEntry.getRegion());
        iotProduct.setStatus(productEntry.getDevStatus());
        if (productEntry.getCreateTime() > 0) {
            iotProduct.setCreateTime(new Date(productEntry.getCreateTime() * 1000)); // 如果需要时间转换
        }
        if (productEntry.getUpdateTime() > 0) {
            iotProduct.setUpdateTime(new Date(productEntry.getUpdateTime() * 1000)); // 如果需要时间转换
        }
        return iotProduct;
    }

    /**
     * 根据产品ID获取产品信息
     */
    @PreAuthorize("@ss.hasPermi('device:product:query')")
    @GetMapping(value = { "/", "/{productId}" })
    public AjaxResult getInfo(@PathVariable(value = "productId", required = false) String productId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(productId))
        {
            IotProduct iotProduct = productService.selectProductById(productId);
            ajax.put(AjaxResult.DATA_TAG, iotProduct);
        }
        return ajax;
    }

    /**
     * 新增产品
     */
    @PreAuthorize("@ss.hasPermi('device:product:add')")
    @Log(title = "产品管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IotProduct product)
    {
        if (StringUtils.isNotEmpty(product.getProductName())
                && IoTConstants.NOT_UNIQUE.equals(productService.checkProductNameUnique(product)))
        {
            return AjaxResult.error("新增产品'" + product.getProductName() + "'失败，产品名称已存在");
        }

        try {
            // 调用腾讯云物联网开发平台创建产品
            Long productType = product.getProductType(); // 0：普通产品，1：网关产品
            String encryptionType = "1"; // 1：证书认证，2：签名认证
            
            CreateStudioProductResponse response = tencentIotService.createProduct(
                product.getProductName(), productType, encryptionType);

            if (response.getProduct() != null) {
                // 设置产品信息
                product.setProductKey(response.getProduct().getProductId());
                product.setProductSecret(""); // 腾讯云不需要产品密钥
                product.setCreateBy(getUsername());
                return toAjax(productService.insertProduct(product));
            } else {
                return AjaxResult.error("新增产品'" + product.getProductName() + "'失败，" + JSON.toJSONString(response));
            }
        } catch (Exception e) {
            return AjaxResult.error("新增产品'" + product.getProductName() + "'失败，" + e.getMessage());
        }
    }

    /**
     * 修改产品
     */
    @PreAuthorize("@ss.hasPermi('device:product:edit')")
    @Log(title = "产品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IotProduct product)
    {
        if (StringUtils.isNotEmpty(product.getProductName())
                && IoTConstants.NOT_UNIQUE.equals(productService.checkProductNameUnique(product)))
        {
            return AjaxResult.error("修改产品'" + product.getProductName() + "'失败，产品名称已存在");
        }

        try {
            // 调用腾讯云物联网开发平台修改产品
            ModifyStudioProductResponse response = tencentIotService.modifyProduct(
                product.getProductKey(), product.getProductName());

            if (response.getProduct() != null) {
                product.setUpdateBy(getUsername());
                return toAjax(productService.updateProduct(product));
            } else {
                return AjaxResult.error("修改产品'" + product.getProductName() + "'失败，" + JSON.toJSONString(response));
            }
        } catch (Exception e) {
            return AjaxResult.error("修改产品'" + product.getProductName() + "'失败，" + e.getMessage());
        }
    }

    /**
     * 删除产品
     */
    @PreAuthorize("@ss.hasPermi('device:product:remove')")
    @Log(title = "产品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{productIds}")
    public AjaxResult delete(@PathVariable String[] productIds)
    {
        AjaxResult ajax = AjaxResult.success();

        // 获取要删除的产品信息
        for (String productId : productIds)
        {
            IotProduct product = productService.selectProductById(productId);
            if (StringUtils.isNotNull(product)) {
                try {
                    // 调用腾讯云物联网开发平台删除产品
                    DeleteStudioProductResponse response = tencentIotService.deleteProduct(product.getProductKey());

                    if (response.getRequestId() != null) {
                        productService.deleteProductById(productId);
                    } else {
                        return AjaxResult.error("删除产品'" + product.getProductName() + "'失败，" + JSON.toJSONString(response));
                    }
                } catch (Exception e) {
                    return AjaxResult.error("删除产品'" + product.getProductName() + "'失败，" + e.getMessage());
                }
            }
        }

        return ajax;
    }
}
